package CrowdCountingMVC.CCModel.Task.ImageTask;

import Const.State;
import CrowdCounting.Model.Util;
import CrowdCountingMVC.CCModel.CrowdCountingModel;

import java.io.File;
import java.util.logging.Level;

public abstract class LoadImageAndNotifyTask implements Runnable {

    CrowdCountingModel crowdCountingModel;
    private String imagePathRoot;
    private int imageFileLength = Integer.valueOf(Util.loadProperty("imageMaxNum"));

    public LoadImageAndNotifyTask(CrowdCountingModel ccm, String imagePathRoot) {
        this.crowdCountingModel = ccm;
        this.imagePathRoot = imagePathRoot;
    }

    @Override
    public void run() {
        while (true) {
            try {
                loadImage();
                if (crowdCountingModel.getShowState() == State.CLOSE) break;
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void loadImage() throws InterruptedException {
        for (int index = 1; index <= imageFileLength; index++) {
            String imagePath = imagePathRoot + "\\image" + index + ".png";
            File imageFile = readImage(imagePath);
            if (imageFile == null) {
                if (crowdCountingModel.getShowState() == State.CLOSE) break;
                else continue;
            }
            setImageAndNotify(imageFile);
            if (!imageFile.delete())
                Util.logger(Level.INFO, "Fail to delete imageFile：" + imagePath);
            while (crowdCountingModel.getShowState() == State.STOP) {
                Util.logger(Level.INFO, "暂停中");
                Util.sleepTime(1000);
            }
        }
        Util.deleteDirectory(new File(imagePathRoot));
    }

    private File readImage(String imagePath) throws InterruptedException {
        int count = 0;
        File imageFile = new File(imagePath);
        while (!Util.fileExistenceCheck(imageFile) || !Util.checkImage(imageFile)) {
            if (crowdCountingModel.getPythonRunTask() != null && !crowdCountingModel.getPythonRunTask().isAlive()) {
                crowdCountingModel.setShowState(State.CLOSE);
            }
            count++;
            if (count == 100 || crowdCountingModel.getShowState() == State.CLOSE) return null;
            Thread.sleep(600);
            imageFile = new File(imagePath);
            Util.logger(Level.INFO, imagePath + " 等待加载中...");
        }
        Util.logger(Level.INFO, imagePath + "加载成功");
        return imageFile;
    }

    public abstract void setImageAndNotify(File imageFile);

}
